/*
 * @Description: 基于fetch和rn的协议工具类，(未经过测试，写着玩的，不建议使用)
 * @Author: jun.fu
 * @Date: 2019-02-19 15:53:53
 * @Last Modified by: jun.fu
 * @Last Modified time: 2019-02-19 15:59:18
 */
import { AsyncStorage, ToastAndroid } from 'react-native'
import sign from './sign.min.js'

let loginFunction = () => {
  console.warn('请登录')
}

let toastFunction = (toastMsg, errCode) => {
  let toast = true
  // if (window.pause) {
  //     toast = false
  if (
    errCode === '401' ||
    errCode === '403' ||
    errCode === '400011' ||
    errCode === '400003'
  ) {
    toast = true
  }
  // }
  if (toast) {
    if (toastMsg && toastMsg !== '') {
      console.log('--------------协议toast--------------')
      console.log(toastMsg)
      // if (window.x_toast) {
      //   window.x_toast.showShortBottom(toastMsg, () => {}, () => {})
      // }
      ToastAndroid.show(toastMsg, ToastAndroid.SHORT)
    }
  }
}

async function ajaxAsyncFetch(api, token, urlString, sendObj, autoEx = true) {
  let url = urlString + ''
  let sessionID = ''
  if (!url.startsWith('/')) {
    url = '/' + url
  }

  url = url + '?token=' + token
  if (api.endsWith('/')) {
    url = api.substring(0, api.length - 1) + url
  } else {
    url = api + url
  }

  try {
    const sessionIDCopy = await AsyncStorage.getItem('XIAOBUSESSION')
    if (sessionIDCopy) {
      sessionID = sessionIDCopy
    }
  } catch (e) {}

  console.log(
    'POST请求日志=>准备发送#####SESSIONID:' +
      sessionID +
      '=>#####请求路径=>' +
      url +
      '#####报文=>' +
      JSON.stringify(sendObj)
  )

  let needLogin = false
  let res = null
  let toastMsg = null
  let logMsg = null
  let errCode = null

  const resCopy = await fetch(url, {
    method: 'POST',
    headers: {
      'X-SESSIONID': sessionID,
      Cookie: 'JSESSIONID=' + sessionID,
      'Content-Type': 'application/JSON;charset=UTF-8'
    },
    body: sign(JSON.stringify(sendObj), token, sessionID)
  })
  if (resCopy.status === 200) {
    res = await resCopy.json()
    console.log(
      'POST请求日志=>响应成功#####请求路径=>' +
        url +
        '#####报文=>' +
        JSON.stringify(res)
    )
    if (res.RSPCD === '000000') {
      return res.BODY
    } else {
      errCode = res.RSPCD + ''
      if (autoEx) {
        switch (errCode) {
          case '400004':
            logMsg = 'SESSION INVALID'
            needLogin = true
            break
          case '400011' || '400003':
            logMsg = '内部错误或RPC Call Failure!!!'
            toastMsg = '服务器开小差了,程序员哥哥正在紧急修复'
            break
          default:
            logMsg = res.RSPMSG
            toastMsg = res.RSPMSG
            break
        }
      }
      dealErr(errCode, toastMsg, logMsg, needLogin)
      throw res
    }
  } else {
    res = resCopy
    if (autoEx) {
      if (res) {
        errCode = res.status + ''
        switch (errCode) {
          case '-1':
            toastMsg = '网络好像开小差咯'
            logMsg =
              'POST请求日志=>请求处理失败!!!,请求路径=>' +
              url +
              '$$$$$错误码=>-1$$$$$错误描述=>TIME_OUT'
            break
          case '403':
            // toastMsg = '网络请求失败,请重试'
            logMsg =
              'POST请求日志=>请求处理失败!!!,请求路径=>' +
              url +
              '$$$$$错误码=>403$$$$$错误描述=>FORBIDDEN'
            needLogin = true
            break

          case '401':
            toastMsg = '网络请求失败,请重试'
            logMsg =
              'POST请求日志=>请求处理失败!!!,请求路径=>' +
              url +
              '$$$$$错误码=>401$$$$$错误描述=>AUTH FORBIDDEN'
          default:
            toastMsg = '网络好像开小差咯'
            logMsg =
              'POST请求日志=>请求处理失败!!!,请求路径=>' +
              url +
              '$$$$$错误码=>' +
              error.status +
              '$$$$$错误描述=>未知错误'
            break
        }
      } else if (
        res &&
        (res.message === 'Network Error' || res.code === 'ECONNABORTED')
      ) {
        toastMsg = '网络好像开小差咯'
      }
      dealErr(errCode, toastMsg, logMsg, needLogin)
    }
    throw res
  }
}

function dealErr(errCode, toastMsg, logMsg, needLogin) {
  if (toastMsg) {
    toastFunction(toastMsg, errCode)
  }
  if (logMsg) {
    console.log(logMsg)
  }

  if (needLogin) {
    loginFunction()
  }
}

export default ajaxAsync
